package com.duoec.doc.service.impl.mock;

import com.duoec.doc.entity.MockConfigItem;
import com.duoec.doc.service.IMocker;
import com.duoec.doc.helper.MockHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xuwenzhen
 * @date 2020/2/1
 */
@Service
public class MapTypeMocker implements IMocker {
    /**
     * mock配置输出的响应
     *
     * @param item 配置
     * @return
     */
    @Override
    public String mock(MockConfigItem item) {
        if (!MockHelper.available(item)) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("{");

        List<MockConfigItem> children = item.getChildren()
                .stream()
                .filter(MockConfigItem::getAvailable)
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(children)) {
            for (int i = 0; i < children.size(); i++) {
                MockConfigItem child = children.get(i);
                if (!MockHelper.available(child)) {
                    continue;
                }
                sb
                        .append("\"")
                        .append(child.getKey())
                        .append("\":");

                IMocker mocker = MockHelper.getMocker(child);
                if (mocker == null) {
                    sb.append("null");
                } else {
                    sb.append(mocker.mock(child));
                }

                if (i != children.size() - 1) {
                    //不是最后一个
                    sb.append(",");
                }
            }
        }

        sb.append("}");
        return sb.toString();
    }

    /**
     * 可处理的基础类型: 0=基本类型 1=枚举 2=pojo 3=collection 4=map 5=数组
     *
     * @return 类型
     */
    @Override
    public Integer getMockType() {
        return 4;
    }
}
